import allure
from selenium.common import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

from page.base_page import BasePage


class InStockStatistics(BasePage):
    __order_management = By.XPATH, "//*[text()='订单管理']"
    __proxy_order = By.XPATH, "//*[text()='代理订单']"
    __proxy_order_list = By.XPATH, "//*[@href = '/order/proxyOrder/proxyOrderApply']"
    __in_stock_amount_summary = By.XPATH, "//*[@class='mb10 search-button']/div"
    __repayment_details_report = By.XPATH, '//*[@href="/statistics/proxyReport/repaymentDetails"]'
    __repayment_statistics = By.XPATH, '//*[@href="/statistics/proxyReport/repayStatisticsProxy"]'
    def goto_proxy_order(self):
        from page.proxy_order_apply_page import ProxyOrderApply
        with allure.step('点击订单管理'):
            self.find_and_click(self.__order_management)
        with allure.step('点击代理订单'):
            self.find_and_click(self.__proxy_order)
        with allure.step('点击订单列表'):
            self.find_and_click(self.__proxy_order_list)
            self.wait(EC.visibility_of_element_located((By.XPATH, "//*[text()='借贷人姓名']")), time_out=10)
        return ProxyOrderApply(self.driver)

    def goto_repayment_statistics(self):
        from page.repayment_statistics_page import RepaymentStatistics
        with allure.step('点击还款统计'):
            self.find_and_click(self.__repayment_statistics)
        return RepaymentStatistics(self.driver)

    def goto_repayment_details_report(self):
        from page.repayment_details_report_page import RepaymentDetailsReport
        with allure.step("点击还款明细报表"):
            self.find_and_click(self.__repayment_details_report)
        return RepaymentDetailsReport(self.driver)

    def get_in_stock_amount_summary(self):
        with allure.step("获取在库总额汇总"):
            in_stock_amount_summary = self.find(self.__in_stock_amount_summary).text
            in_stock_amount_summary = in_stock_amount_summary.split(":")[1]
        return float(in_stock_amount_summary)

    def get_product_in_stock_amount(self, product_name):
        with allure.step(f"获取{product_name}的在库总额"):
            product_in_stock_details = []
            try:
                self.wait(EC.presence_of_element_located((By.XPATH, f"//*[text()='{product_name}']")))
                for i in range(4, 6):
                    product_in_stock_details.append(
                        float(self.find(By.XPATH, f"//*[text()='{product_name}']/../../td[{i}]/div").text))
            except StaleElementReferenceException:
                pass
        return product_in_stock_details
